package com.fadadianqi.mall.service;

import com.fadadianqi.commons.PrimaryKeyCreator;
import com.fadadianqi.mall.dao.MemberDAO;
import com.fadadianqi.mall.exception.MemberException;
import com.fadadianqi.mall.model.Member;
import com.yeqiangwei.commons.util.StringHelper;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class MemberService {

    public void reg(Member member) throws MemberException {
        if (ValidatorHelper.isEmpty(member.getName())) {
            throw new MemberException("exception.member.reg.required.name");
        } else if (ValidatorHelper.isEmpty(member.getPassword())) {
            throw new MemberException("exception.member.reg.required.password");
        }
        //
        Member m = null;
        m = getByName(member.getName());
        if (null != m) {
            throw new MemberException("exception.member.reg.duplicate.name");
        }
        if (ValidatorHelper.isNotEmpty(member.getEmail())) {
            m = getByEmail(member.getEmail());
            if (null != m) {
                throw new MemberException("exception.member.reg.duplicate.email");
            }
        }
        if (ValidatorHelper.isNotEmpty(member.getMobile())) {
            m = getByMobile(member.getMobile());
            if (null != m) {
                throw new MemberException("exception.member.reg.duplicate.mobile");
            }
        }
        String md5Pwd = StringHelper.MD5(member.getPassword());
        member.setPassword(md5Pwd);
        member.setAddTime(new Date());
        member.setId(PrimaryKeyCreator.create());
        memberDAO.create(member);
    }

    public Member getByEmail(String email) {
        return memberDAO.getByEmail(email);
    }

    public Member getById(String id) {
        return memberDAO.getById(id);
    }

    public Member getByName(String name) {
        return memberDAO.getByName(name);
    }

    public Member getByMobile(String mobile) {
        return memberDAO.getByMobile(mobile);
    }

    @Autowired
    private MemberDAO memberDAO;
}
